const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const fs = require("fs");
let win;
function createWindow() {
  win = new BrowserWindow({
    width: 1800,
    height: 1000,
    icon: path.join(__dirname, "./public/favicon.ico"),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // 禁用Web安全策略
    },
  });
  win.loadFile("./dist/index.html"); //项目入口文件

  // win.loadURL("http://localhost:8080/"); //项目入口文件
  // win.webContents.openDevTools(); // 打开调试器

  win.setMenu(null); //	隐藏顶部菜单
  // win.loadURL("./dist/index.html");
  win.on("closed", () => {
    win = null;
  });
}
app.on("ready", createWindow);

ipcMain.on("upload-image", (event, file) => {
  const savepath = `C:\\images\\${file.project}`;
  const imagePath = path.join(savepath, file.name);
  console.log("file");
  if (fs.existsSync(path.join(savepath))) {
    // 将Buffer写入文件
    fs.writeFile(imagePath, Buffer.from(file.data), (err) => {
      if (err) {
        console.error("写入图片失败:", err);
      } else {
        console.log("图片保存成功:", imagePath);
      }
    });
  } else {
    fs.mkdir(path.join(savepath), (err) => {
      if (err) {
        console.log(err);
        return;
      }

      // 将Buffer写入文件
      fs.writeFile(imagePath, Buffer.from(file.data), (err) => {
        if (err) {
          console.error("写入图片失败:", err);
        } else {
          console.log("图片保存成功:", imagePath);
        }
      });
    });
  }
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (win === null) {
    createWindow();
  }
});
